package tpl;

import com.jfinal.config.Constants;
import com.jfinal.config.Handlers;
import com.jfinal.config.Interceptors;
import com.jfinal.config.JFinalConfig;
import com.jfinal.config.Plugins;
import com.jfinal.config.Routes;
import com.jfinal.template.Engine;
import com.jfinal.server.undertow.UndertowServer;
import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.OrderedFieldContainerFactory;
import com.jfinal.plugin.activerecord.dialect.SqlServerDialect;
import com.jfinal.plugin.druid.DruidPlugin;

public class ProConfig extends JFinalConfig {
	static Prop p;

	public static void main(String[] args) {
		UndertowServer.create(ProConfig.class).setDevMode(true).setPort(8080)
    	.configWeb( builder -> {
			// 配置 Filter
			builder.addFilter("CORS", "com.thetransactioncompany.cors.CORSFilter");
			builder.addFilterInitParam("CORS", "cors.allowOrigin", "*");
			builder.addFilterInitParam("CORS", "cors.supportedMethods", "GET, POST, HEAD, PUT, DELETE,OPTIONS");
			builder.addFilterInitParam("CORS", "cors.supportedHeaders", "Accept, Origin, X-Requested-With,tokenId,Content-Type, Last-Modified,lang,entCode,x-form-id");
			builder.addFilterInitParam("CORS", "cors.exposedHeaders", "Set-Cookie");
			builder.addFilterInitParam("CORS", "cors.supportsCredentials", "true");
			builder.addFilterUrlMapping("CORS", "/*");
		})
		.start();
	}

	/**
	 * 配置常量
	 */
	public void configConstant(Constants me) {
		loadConfig();

		me.setDevMode(p.getBoolean("devMode", false));

		/**
		 * 支持 Controller、Interceptor、Validator 之中使用 @Inject 注入业务层，并且自动实现 AOP
		 * 注入动作支持任意深度并自动处理循环注入
		 */
		me.setInjectDependency(true);

		// 配置对超类中的属性进行注入
		me.setInjectSuperClass(true);
		// me.setBaseUploadPath("\\xxx");
	}

	public void configRoute(Routes me) {
		me.add("/main", MainController.class);
	}

	public void configEngine(Engine me) {
	}

	public void configHandler(Handlers me) {
	}

	/**
	 * PropKit.useFirstFound(...) 使用参数中从左到右最先被找到的配置文件
	 * 从左到右依次去找配置，找到则立即加载并立即返回，后续配置将被忽略
	 */
	static void loadConfig() {
		if (p == null) {
			p = PropKit.useFirstFound("config-pro.txt", "config-dev.txt");
		}
	}

	/**
	 * 配置插件
	 */
	public void configPlugin(Plugins me) {
		// 配置 druid 数据库连接池插件
		DruidPlugin druidPlugin = new DruidPlugin(p.get("jdbcUrl"), p.get("user"), p.get("password").trim());
		me.add(druidPlugin);

		// // 配置ActiveRecord插件
		ActiveRecordPlugin arp = new ActiveRecordPlugin(druidPlugin);
		arp.setContainerFactory(new OrderedFieldContainerFactory());
		arp.setShowSql(true);// 这句话就是ShowSql
		// arp.setDialect(new SqlServerDialect());
		// // 所有映射在 MappingKit 中自动化搞定
		// // arp.addMapping("blog", "id", );
		me.add(arp);
	}

	public static DruidPlugin createDruidPlugin() {
		loadConfig();

		return new DruidPlugin(p.get("jdbcUrl"), p.get("user"), p.get("password").trim());
	}

	@Override
	public void configInterceptor(Interceptors me) {
		// me.add(new CorsInc());
	}
}